﻿using Enterprise_Get.API.Infrastructures.Interfaces;
using MediatR;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.BasicInformation.Departments;
using THE_WIND_RISES.Common.Dtos;

namespace Enterprise_Get.API.Application.Commands.BasicInformations
{
    public class DepartmentQueryHandler : IRequestHandler<DepartmentQueryCommand, THE_WIND_RISES.Common.Dtos.Result>
    {
        /// <summary>
        /// 部门仓储
        /// </summary>
        private readonly IBaseRepositoryGet<Department> departmentRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository"></param>
        public DepartmentQueryHandler(IBaseRepositoryGet<Department> departmentRepository)
        {
            this.departmentRepository = departmentRepository;
            
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DepartmentQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new THE_WIND_RISES.Common.Dtos.Result() { Code = (int)CommonErrorCodes.Search };

            try
            {
                var sql = "select * from Department";
                var list = departmentRepository.GetAll(sql);

                if (!string.IsNullOrEmpty(request.DepartmentName))
                {
                    list = list.Where(x => x.DepartmentName.Contains(request.DepartmentName)).ToList();
                }

                var totalCount = list.Count();

                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);

                list = list.OrderBy(x => x.DepartmentId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

                var aa = new
                {
                    list,
                    totalCount,
                    totalPage
                };

                if (list != null)
                {
                    result.Data = aa;

                    result.Msg = "显示成功";
                }
                else
                {
                    result.Msg = "显示失败";
                }
            }
            catch (Exception)
            {

                throw;
            }

            return result;
        }
    }
}
